package com.demo.apparel.service.web.Impl;

import com.demo.apparel.dto.CategoryDTO;
import com.demo.apparel.dto.ClothesByCategoryDTO;
import com.demo.apparel.dto.web.CategoryPageQueryDTO;
import com.demo.apparel.dto.web.ClothesTypeAddDTO;
import com.demo.apparel.entity.Category;
import com.demo.apparel.entity.ClothesType;
import com.demo.apparel.mapper.web.ClothesTypeMapper;
import com.demo.apparel.mapper.web.WebCategoryMapper;
import com.demo.apparel.mapper.web.WebClothesByCategoryMapper;
import com.demo.apparel.service.web.WebCategoryService;
import com.demo.apparel.vo.PageVO;
import com.demo.apparel.vo.web.CategoryWithSubExportVO;
import com.demo.apparel.vo.web.CategoryWithSubVO;
import com.demo.apparel.vo.web.ClothesTypeSimpleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WebCategoryServiceImpl implements WebCategoryService {

    @Autowired
    private WebCategoryMapper webCategoryMapper;

    @Autowired
    private WebClothesByCategoryMapper clothesMapper;

    @Autowired
    private ClothesTypeMapper clothesTypeMapper;
    /**
     * 增加大分类
     * @param dto
     */
    @Override
    public boolean addCategory(CategoryDTO dto) {
        Integer categoryFromDto = dto.getCategory();

        Integer categoryToUse = null;

        // 如果前端传了 category，先判断是否存在
        if (categoryFromDto != null) {
            int exists = webCategoryMapper.existsCategory(categoryFromDto);
            if (exists > 0) {
                throw new RuntimeException("该分类编号已存在！");
            }
            categoryToUse = categoryFromDto;
        } else {
            // 没传category，或者传null，随机生成一个唯一的1~15之间数字
            Random random = new Random();
            int maxTry = 50;  // 最多尝试50次避免死循环
            for (int i = 0; i < maxTry; i++) {
                int candidate = random.nextInt(15) + 1; // 生成1~15
                int exists = webCategoryMapper.existsCategory(candidate);
                if (exists == 0) {
                    categoryToUse = candidate;
                    break;
                }
            }
            if (categoryToUse == null) {
                throw new RuntimeException("无法生成唯一的分类编号，请检查数据库已有数据！");
            }
        }

        Category category = new Category();
        category.setId(UUID.randomUUID().toString().replace("-", ""));
        category.setCategory(categoryToUse);
        category.setCategoryName(dto.getCategoryName());

        int rows = webCategoryMapper.insertCategory(category);
        return rows > 0;
    }

    /**
     * 获取所以所有分类
     * @return
     */
    @Override
    public List<CategoryDTO> getAllCategories() {
        return webCategoryMapper.getAllCategories();
    }

    /**
     * 获取某分类的数据例如（上装：)
     */
    @Override
    public PageVO<ClothesByCategoryDTO> getClothesByCategory(int category, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<ClothesByCategoryDTO> records = clothesMapper.getClothesByCategory(category, offset, pageSize);
        long total = clothesMapper.getClothesCountByCategory(category);
        return new PageVO<>(records, total, pageNum, pageSize);
    }

    /**
     *
     * @param query
     * @return
     */
    @Override
    public PageVO<CategoryWithSubVO> getCategoryWithSubPage(CategoryPageQueryDTO query) {
        List<Map<String, Object>> categoryList = webCategoryMapper.getAllCategorieses();
        List<Map<String, Object>> clothesTypeList = clothesTypeMapper.getAllClothesType();

        // 排序：按 category 整型字段升序
        categoryList.sort(Comparator.comparingInt(cat -> (Integer) cat.get("category")));

        // 搜索关键词处理
//        String rawSearch = query.getSearch();
        // 改为
        String rawSearch = query.getCategoryName();
        final String search = rawSearch == null ? null : rawSearch.trim().toLowerCase();

        List<CategoryWithSubVO> allCategoryVos = new ArrayList<>();

        for (Map<String, Object> cat : categoryList) {
            Integer categoryId = (Integer) cat.get("category");
            String categoryName = (String) cat.get("category_name");
            String id = (String) cat.get("id");  // 大类的 ID

            // 找出该分类对应的小类列表
            List<ClothesTypeSimpleVO> subList = clothesTypeList.stream()
                    .filter(item -> {
                        String typeCat = (String) item.get("category");
                        try {
                            return Integer.parseInt(typeCat) == categoryId;
                        } catch (Exception e) {
                            return false;
                        }
                    })
//                    .map(item -> new ClothesTypeSimpleVO(
//                            (String) item.get("id"),
//                            (String) item.get("type_name")
//                    ))
                    .map(item -> {
                        ClothesTypeSimpleVO vo = new ClothesTypeSimpleVO(
                                (String) item.get("id"),
                                (String) item.get("type_name")
                        );
                        // 取出 keywords 字段（假设是字符串，逗号分隔）
                        Object keywordsObj = item.get("keywords");
                        if (keywordsObj != null) {
                            String keywordsStr = keywordsObj.toString();
                            List<String> keywords = Arrays.stream(keywordsStr.split(","))
                                    .map(String::trim)
                                    .filter(s -> !s.isEmpty())
                                    .collect(Collectors.toList());
                            vo.setKeywords(keywords);
                        }
                        return vo;
                    })

                    .collect(Collectors.toList());

            // 搜索过滤
            boolean matchesSearch = true;
            if (search != null && !search.isEmpty()) {
                boolean categoryMatch = categoryName.toLowerCase().contains(search);
                boolean subCategoryMatch = subList.stream()
                        .anyMatch(sub -> sub.getTypeName().toLowerCase().contains(search));
                matchesSearch = categoryMatch || subCategoryMatch;
            }

            if (!matchesSearch) continue;

            // 组装 VO
            CategoryWithSubVO vo = new CategoryWithSubVO();
            vo.setId(id);  // 加上大类ID
            vo.setCategory(categoryId);
            vo.setCategoryName(categoryName);
            vo.setCount(subList.size());
            vo.setSubCategories(subList);

            allCategoryVos.add(vo);
        }

        // 分页处理
        int total = allCategoryVos.size();
        int fromIndex = Math.min((query.getPageNum() - 1) * query.getPageSize(), total);
        int toIndex = Math.min(query.getPageNum() * query.getPageSize(), total);
        List<CategoryWithSubVO> pageList = allCategoryVos.subList(fromIndex, toIndex);

        return new PageVO<>(pageList, total, query.getPageNum(), query.getPageSize());
    }



    // 生成唯一五位数ID
    private String generateUniqueId() {
        Random random = new Random();
        String id;
        int count;
        do {
            id = String.valueOf(10000 + random.nextInt(90000));
            count = clothesTypeMapper.countById(id);
        } while (count > 0);
        return id;
    }

    /**
     *
     * @param dto
     */
    @Override
    public void addClothesType(ClothesTypeAddDTO dto) {
        String categoryName = webCategoryMapper.getCategoryNameByCategory(dto.getCategory());
        if (categoryName == null) {
            throw new RuntimeException("分类不存在");
        }
        String newId = generateUniqueId();
        ClothesType clothesType = new ClothesType();
        clothesType.setId(String.valueOf(newId));
        clothesType.setTypeName(dto.getTypeName());
        clothesType.setCategory(dto.getCategory());
        clothesType.setCreateTime(LocalDateTime.now());
        clothesType.setSort(0);
        if (dto.getKeywords() != null && !dto.getKeywords().isEmpty()) {
            clothesType.setKeywords(String.join(",", dto.getKeywords()));
        }

        clothesTypeMapper.insertClothesType(clothesType);
    }

    @Override
    public boolean updateClothesType(ClothesTypeAddDTO dto) {
        ClothesType clothesType = new ClothesType();
        BeanUtils.copyProperties(dto, clothesType);
        // keywords 是 List<String>，转换成逗号分隔字符串
        if (dto.getKeywords() != null && !dto.getKeywords().isEmpty()) {
            clothesType.setKeywords(String.join(",", dto.getKeywords()));
        } else {
            clothesType.setKeywords("");
        }
        // category从Integer转String
        clothesType.setCategory(dto.getCategory());

        int rows = clothesTypeMapper.updateClothesType(clothesType);
        return rows > 0;
    }

    /**
     * 删除大类的
     * @param id
     * @return
     */
    @Override
    public boolean deleteCategoryById(String id) {
        // 通过大类ID查询对应的category（整数标识）
        Integer category = webCategoryMapper.getCategoryById(id);
        if (category == null) {
            return false;  // 找不到对应大类
        }

        // 删除该category下所有小类
        clothesTypeMapper.deleteByCategory(category);

        // 删除大类
        int rows = webCategoryMapper.deleteCategoryById(id);

        return rows > 0;
    }

    /**
     * 删除小分类
     * @param id
     * @return
     */
    @Override
    public boolean deleteClothesTypeById(String id) {
        int rows = clothesTypeMapper.deleteById(id);
        return rows > 0;
    }

    /**
     * 更新大类名字
     * @param category
     * @param categoryName
     * @return
     */
    @Override
    public boolean updateCategoryName(Integer category, String categoryName) {
        if (category == null || categoryName == null || categoryName.trim().isEmpty()) {
            throw new IllegalArgumentException("分类编号和名称不能为空");
        }
        int rows = webCategoryMapper.updateCategoryName(category, categoryName.trim());
        return rows > 0;
    }

    @Override
    public List<CategoryWithSubExportVO> getExportData() {
        return webCategoryMapper.exportCategoryWithSub();
    }
}

